const {
  reviewInfo,
  reviewOpen
} = require('../../../api/api')
const {
  rpxTopx
} = require('../../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: getApp().globalData.windowHeight,
    bottomLift: getApp().globalData.bottomLift,
    currentIndex: 0,
    List: [],
    width: 0,
    id: 2,
    circleWidth: 0,
    queList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'],
    count: 0,
    countTimer: null,
    maxLength: 60,
    studentId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
    if (options.studentId) {
      console.log(options.studentId)
      if (options.studentId !== 'undefined' && options.studentId !== undefined) {
        this.setData({
          studentId: options.studentId
        })
      }
    }
    this.getList()
  },
  drawProgressbg: function (id) {
    // 使用 wx.createContext 获取绘图上下文 context(该接口已经不再维护了)
    var canvasWidth = rpxTopx(380)
    var radius = Math.floor(canvasWidth / 2)
    var radiusDot = radius + 10
    // console.log(radius)
    var ctx = wx.createCanvasContext(id)
    ctx.setLineWidth(12); // 设置圆环的宽度
    ctx.setStrokeStyle('#E6E6E6'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(radiusDot, radiusDot, radius, 0, 2 * Math.PI, false);
    //设置一个原点(100,100)，半径为100的圆的路径到当前路径
    ctx.stroke(); //对当前路径进行描边
    ctx.draw(false, () => {
      // 延迟保存图片，解决生成图片错位bug。
      setTimeout(() => {
        this.canvasToTempImage();
      }, 400);
    });
  },
  canvasToTempImage() {
    wx.canvasToTempFilePath({
      canvasId: "gg",
      success: (res) => {
        let tempFilePath = res.tempFilePath;
        this.setData({
          imagePath: tempFilePath,
        });
      }
    }, this);
  },
  drawCircle: function (step) {
    var canvasWidth = rpxTopx(380)
    var radius = Math.floor(canvasWidth / 2)
    var radiusDot = radius + 10
    var context = wx.createCanvasContext('canvasProgress');
    // 设置渐变
    var gradient = context.createLinearGradient(200, 100, 100, 200);
    gradient.addColorStop("0", "#fcce00");
    gradient.addColorStop("0.5", "#fca400");
    gradient.addColorStop("1.0", "#fcce00");

    context.setLineWidth(12);
    context.setStrokeStyle(gradient);
    context.setLineCap('round')
    context.beginPath();
    // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
    context.arc(radiusDot, radiusDot, radius, Math.PI / 2, step * Math.PI - (-Math.PI / 2), false);
    context.stroke();
    context.draw()
  },

  countInterval: function () {
    const {
      maxLength,
      count
    } = this.data
    // 设置倒计时 定时器 每100毫秒执行一次，计数器count+1 ,耗时6秒绘一圈
    if (this.data.count <= maxLength) {
      /* 绘制彩色圆环进度条 
      注意此处 传参 step 取值范围是0到2，
      所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2
      */
      this.drawCircle(this.data.count / (maxLength / 2))
    } else {
      this.setData({
        progress_txt: "匹配成功"
      })
    }
  },
  next() {
    var {
      count
    } = this.data
    this.setData({
      count: count + 1
    })
    this.countInterval()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.drawProgressbg('canvasProgressbg');
    // this.countInterval()
  },

  async getList() {
    const {
      id
    } = this.data
    const {
      result
    } = await reviewInfo(id)
    result.map((item) => {
      item['answer'] = ''
      item['value'] = ''

      item.subjectAnswerList.map((answer) => {
        answer['checked'] = false
      })
    })
    this.setData({
      List: result,
      maxLength: result.length
    })
  },

  radioChange(e) {
    let {
      List,
      currentIndex,
      maxLength,
      count
    } = this.data
    const {
      answer,
      value
    } = e.currentTarget.dataset
    answer.map((item) => {
      if (item.id == value) {
        List[currentIndex].answer = item.value
        List[currentIndex].value = item.id
      }
    })
    const len = List.length
    const index = currentIndex + 1
    const width = (index / len) * 100
    this.setData({
      List,
      width: width + '%'

    })

    if (currentIndex === List.length - 1) {
      this.setData({
        currentIndex: currentIndex,
        circleWidth: 100,
        count: maxLength
      })
      this.countInterval()
      setTimeout(() => {
        this.submit()
      }, 500);


    } else {
      // if(type){
      //   this.setData({
      //     currentIndex: currentIndex + 1,
      //     width: width + '%'
      //   })
      //   return
      // }
      setTimeout(() => {
        this.setData({
          currentIndex: currentIndex + 1,
          width: width + '%',
          circleWidth: width.toFixed(),
          count: count + 1
        })
        this.countInterval()
      }, 500);

    }


  },
  async submit() {
    wx.showLoading({
      title: '正在提交',
    })
    const {
      List,
      studentId
    } = this.data
    const newArr = []
    List.map((item) => {
      const newItem = {
        subjectId: item.id,
        answer: item.answer,
        reviewId: this.data.id
      }
      newArr.push(newItem)
    })
    let params = {}
    if (studentId) {
      params.studentId = studentId
    }

    const {
      result
    } = await reviewOpen(this.data.id, newArr, params)
    if (result) {
      wx.hideLoading()
      wx.redirectTo({
        url: '/pages/users/result/index?param=' + encodeURIComponent(JSON.stringify(result)),
      })
    }
  },
  async prev() {
    var {
      List,
      count,
      currentIndex
    } = this.data
    const newArr = []
    const len = List.length
    const width = (currentIndex / len) * 100
    List.map((item) => {
      const newItem = {
        subjectId: item.id,
        answer: item.answer,
        reviewId: this.data.id
      }
      newArr.push(newItem)
    })
    currentIndex = currentIndex - 1
    this.setData({
      currentIndex,
      circleWidth: parseInt(width),
      count: count - 1
    })
    this.countInterval()
  },
  onShareAppMessage: function () {
    return {
      title: '职业测评',
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  },
})